<template>
  <div>
    <my-header></my-header>

    <el-card class="card">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      >
      </el-alert>

      <div class="div">
        <p>选择商品分类 :</p>
        <el-cascader
          v-model="value"
          :options="options"
          :props="{
            expandTrigger: 'hover',
            label: 'cat_name',
            value: 'cat_id',
          }"
          @change="handleChange"
        ></el-cascader>
      </div>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isEdit"
            @click="dialogFormVisible = true"
            >添加参数</el-button
          >
          <el-table :data="list1" style="width: 100%">
            <el-table-column type="expand">
              <!--  -->
              <template slot-scope="props">
                <el-tag
                  :key="index"
                  v-for="(tag,index) in props.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(props.row,index)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="props.row.inputVisible"
                  v-model="props.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(props.row)"
                  @blur="handleInputConfirm(props.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(props.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isEdit"
            @click="dialogFormVisible = true"
            >添加属性</el-button
          >
          <el-table :data="list2" style="width: 100%">
            <el-table-column type="expand">
              <!-- slot-scope="props" -->
          <template slot-scope="props">
                <el-tag
                  :key="index"
                  v-for="(tag,index) in props.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(props.row,index)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="props.row.inputVisible"
                  v-model="props.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(props.row)"
                  @blur="handleInputConfirm(props.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(props.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
        
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 模态框 -->
    <el-dialog :title="'编辑'+text" :visible.sync="dialogFormVisible1">
      <el-form
        :model="ruleForm1"
        ref="ruleForm1"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="text" prop="cat_name">
          <el-input v-model="ruleForm1.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm1('ruleForm1')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog :title="'添加'+text" :visible.sync="dialogFormVisible">
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="text" prop="cat_name">
          <el-input v-model="ruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCate, getCateList, getCateAttr,getCatePut,getCateDel} from "../../api/cate";
import myHeader from "../../components/myHeader.vue";
export default {
  components: { myHeader },
  data() {
    return {
      // tag标签的名字数据
      dynamicTags: ["标签一", "标签二", "标签三"],
      // input的显示隐层
      inputVisible: false,
      // input框的model
      inputValue: "",
      // 级联选择器的model
      value: [],
      // 级联选择器的数据
      options: [],
      // tab的model，用来区别动态/静态
      activeName: "many",
      // 表格数据
      list1: [],
      list2: [],
      obj: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      dialogFormVisible1: false,
      dialogFormVisible: false,
      ruleForm1: {
        attr_name: "",
        id:this.cateId
      },
      ruleForm: {
        attr_name: "",
      },
    };
  },
  computed: {
    text(){
      if(this.activeName=="many"){
        return "动态参数"
      }else{
        return "静态属性"
      }
    },
    isEdit() {
      if (this.value.length === 3) {
        return false;
      } else {
        return true;
      }
    },
    cateId() {
      //分类id
      if (this.value.length === 3) {
        console.log(this.value[2], "value");
        return this.value[2];
      }
    },
  },
  created() {
    this.getList();
  },
  methods: {
    // 点击删除该条tag标签
    handleClose(row,index) {
      console.log(row,index,"tag")
      row.attr_vals.splice(index, 1);
      this.getAttr(row)
    },
    // 点击input框出现
    showInput(row) {
      row.inputVisible = true;
      // 一个延迟函数，内部是一个promise
      this.$nextTick(() => {
        //js原生方法,获取焦点的 click()
        this.$refs.saveTagInput.focus();
      });
    },
    //  在input中填写数据后进行添加
    async handleInputConfirm(row) {
      console.log("row",row)
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
            // 如果没有return，则证明输入的内容，需要做后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
     this.getAttr(row)
    },
    // 点击的该条tag数据。进行传参调用
    async getAttr(row){
            row.inputVisible = false
      let obj={
        id:this.cateId,
        attr_id:row.attr_id,
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(",")
      }
       let res= await getCatePut(obj)
       console.log(res,"resPutTag")
    },

    // 标签页点击切换
    handleClick(tab, event) {
      console.log(tab, event, "tab");
      this.getData()
    },
    // 表格数据的单独获取
    async getData(){
      if (this.value.length !== 3) {
        this.value = [];
        return false;
      }
      let res = await getCateList({
        cate_id: this.cateId,
        sel: this.activeName,
      });
      console.log(res, "resOnly");
      if(res.meta.status==200){
                res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          // 控制文本框的显示与隐藏
          item.inputVisible = false;
          // 文本框中输入的值
          item.inputValue = "";
        });

             if(this.activeName=="only"){
        this.list2=res.data
       }else if(this.activeName=="many"){
        this.list1=res.data
       }
       }
    },
    // 层级选择器改变时所触发
     handleChange(value) {
      console.log(value);
      console.log(this.cateId, "cateId");
     
     this.getData()

      // this.getTab()
      
    },
    // 层级选择器的渲染
    async getList() {
      let res = await getCate(this.obj);
      console.log(res, "resList");
      if (res.meta.status == 200) {
        this.options = res.data.result;
      }
    },

   
    // 编辑
    submitForm1(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // alert('submit!');
          console.log(this.ruleForm1,"1111")
          let res = await getCatePut(this.ruleForm1);
          console.log(res, "resAdd");
          if (res.meta.status == 200) {
            this.getData();
            this.dialogFormVisible1 = false;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogFormVisible1=true
      this.ruleForm1={
        id:this.cateId,
        attr_vals:row.attr_vals.join(","),
        attr_id:row.attr_id,
        attr_name:row.attr_name,
        attr_sel:this.activeName,
      }
    },
    // 删除
    handleDelete(index, row) {
      console.log(index, row);
              this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          
          let res=await getCateDel({
            id:this.cateId,
            attr_id:row.attr_id
          })
          console.log(res,"resDel")
          if(res.meta.status==200){
            this.getData()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 添加
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let obj={
            id:this.cateId,
            attr_name:this.ruleForm.attr_name,
            attr_sel:this.activeName,
          }
          // alert('submit!');
          let res = await getCateAttr(obj);
          console.log(res, "resAdd");
          if (res.meta.status == 201) {
            this.getData();
            this.dialogFormVisible = false;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.card {
  margin-top: 20px;
}
.div {
  display: flex;
  justify-content: flex-start;
  height: 35px;
  line-height: 35px;
  margin-top: 20px;
}
.el-tabs {
  margin-top: 20px;
}
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>